

require( "mysql" )

print("Connect test!")
local db, error = mysql.connect("127.0.0.1", "root", "mysql", "gmod_test")
if (db == 0) then print(tostring(error) .. "\n") return end
print("connection opened - " .. db .. "!\n");
print("------------------------------------------------------------------\n");
print("Escape test!")
local esc, error = mysql.escape(db, "\r\n\"");
if (esc) then
	print("esc=" .. esc .. "\n")
else
	print(tostring(error) .. "\n");
end
print("------------------------------------------------------------------\n");
print("Simple test!")
test, isok, error = mysql.query(db, "SELECT 1 + 1");
if (test) then
	PrintTable(test)
end
if (!isok) then
	print(tostring(error) .. "\n");
end
print("------------------------------------------------------------------\n");
print("Insert test!")
for i=1,100 do
	local steamid = "STEAM_" .. math.random(0,3) .. ":" .. math.random(0,3) .. ":" .. math.random(1,100000)
	local name = "Player" .. math.random(1,100000)
	result, isok, error = mysql.query(db, "INSERT INTO names (SteamId,Name) VALUES('" .. steamid .. "','" .. name ..  "');");
	print(i)
	if (!isok) then
		print(tostring(error) .. "\n");
		break;
	end
end

print("------------------------------------------------------------------\n");
print("Non-threaded test!")
test, isok, error = mysql.query(db, "SELECT * FROM names");
if (test) then
	PrintTable(test)
end
if (!isok) then
	print(tostring(error) .. "\n");
end

print("------------------------------------------------------------------\n");
print("Threaded test!")
thread, isok, error = mysql.query(db, "SELECT * FROM names", mysql.QUERY_NOBLOCK);
if (thread) then
	print("thread=" .. thread .. "\n")
	
	function printResults(threadid)
		if (mysql.query_complete(threadid)) then
			print("thread=" .. threadid .. " -> finished!")
			test, isok, error = mysql.query_read(threadid)
			if (test) then
				PrintTable(test)
			end
			if (!isok) then
				print( tostring(error) );
			end
			mysql.query_cleanup(threadid)
			
			print("------------------------------------------------------------------\n");
			print("Disconnect on completion!")
			local succ, error = mysql.disconnect(db)
			if (not succ) then
				print( error );
			end
			print("connection closed!\n");
		else
			print("thread=" .. threadid .. " -> still not finished")
			timer.Simple(1, printResults, threadid)
		end
	end
	
	timer.Simple(0, printResults, thread)
end
if (!isok) then
	print(tostring(error) .. "\n");

	print("------------------------------------------------------------------\n");
	print("Disconnect on error!")
	local succ, error = mysql.disconnect(db)
	if (not succ) then
		print( error );
	end
	print("connection closed!\n");
end



